export function parseTime(time, cFormat) {
  if (!time) {
    return ''
  }
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}
/**
 * @description 打开窗口
 * @author jinlei
 * @date 2020-02-04
 * @export
 * @param {*} url 地址
 * @param {*} title 标题
 * @param {*} w 宽度
 * @param {*} h 高度
 */
export function windowOpen(url, title, w, h) {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height

  const left = ((width / 2) - (w / 2)) + dualScreenLeft
  const top = ((height / 2) - (h / 2)) + dualScreenTop
  const newWindow = window.open(url, title, 'channelmode=yes,toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus()
  }
}

// 网址验证
export function isUrl(data) {
  const strUrl = '^((https|http|ftp|rtsp|mms)?://)' +
                "?(([0-9a-zA-Z_!~*'().&=+$%-]+: )?[0-9a-zA-Z_!~*'().&=+$%-]+@)?" +
                '(([0-9]{1,3}\.){3}[0-9]{1,3}' +
                '|' +
                "([0-9a-zA-Z_!~*'()-]+\.)*" +
                '([0-9a-zA-Z][0-9a-z-A-Z]{0,61})?[0-9a-zA-Z]\.' +
                '[a-zA-Z]{2,6})' +
                '(:[0-9]{1,4})?' +
                '((/?)|' +
                "(/[0-9a-zA-Z_!~*'().;?:@&=+$,%#-]+)+/?)$"
  const urlDemo = new RegExp(strUrl)
  return urlDemo.test(data)
}

// 删除html标签
export function removeTags(data) {
  if (data) {
    return data.replace(/<[^>]+>|&nbsp;|\n|\|+|\r/g, '')
  } else {
    return ''
  }
}
// 获取字符串字节长度
export function getByteLength(str) {
  if (typeof str != 'string' && typeof str != 'number') return 0
  if (typeof str == 'number') str += ''
  const temp = str.replace(/[\u4e00-\u9fff]|[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/g, 'aa')
  return temp.length
}
// 检测数据类型
export function checkType(obj) {
  return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}

// 号码通用
export function checkTel(data) {
  const reg = /^1[3456789]\d{9}$|^0\d{2,3}-?\d{7,8}$|^\d{7,8}$/
  return reg.test(data)
}

// 现在文件
export function downloadFile(fileUrl, fileName = '') {
  // 浏览器支持fetch则用blob下载，避免浏览器点击a标签，跳转到新页面预览的行为
  return new Promise((resolve, reject) => {
    if (window.fetch) {
      fetch(fileUrl)
        .then(res => res.blob())
        .then(blob => {
          const a = document.createElement('a')
          const url = window.URL.createObjectURL(blob)
          a.href = url
          a.download = fileName
          a.click()
          window.URL.revokeObjectURL(url)
          resolve()
        }).catch(reject)
    } else {
      const a = document.createElement('a')
      a.href = fileUrl
      a.target = '_blank'
      a.download = fileName
      a.click()
      resolve()
    }
  })
}

export function deepCopy(obj) {
  let result
  const type = checkType(obj)
  if (type === 'array' || type === 'object') {
    result = type === 'array' ? [] : {}
    Object.keys(obj).forEach(index => {
      if (typeof obj[index] === 'object' && obj[index] !== null) {
        result[index] = deepCopy(obj[index])
      } else {
        result[index] = obj[index]
      }
    })
  } else {
    result = obj
  }
  return result
}
